package com.unionftech.common.permissions;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.fragment.app.FragmentActivity;

import com.unionftech.common.utils.LogUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class JumpPermissionUtils {
    private static final String MANUFACTURER_HUAWEI = "Huawei";//华为
    private static final String MANUFACTURER_MEIZU = "Meizu";//魅族
    private static final String MANUFACTURER_XIAOMI = "Xiaomi";//小米
    private static final String MANUFACTURER_SONY = "Sony";//索尼
    private static final String MANUFACTURER_OPPO = "OPPO";
    private static final String MANUFACTURER_LG = "LG";
    private static final String MANUFACTURER_VIVO = "vivo";
    private static final String MANUFACTURER_COOLPAD = "Coolpad";
    public static final int PERMISSION_SETTING_FOR_RESULT = 0x001;

    public static void gotoSetting(FragmentActivity activity) {
        try {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            activity.startActivityForResult(intent, PERMISSION_SETTING_FOR_RESULT);
        } catch (Exception e) {
            e.printStackTrace();
            String name = Build.MANUFACTURER;
            LogUtils.d("jumpPermissionPage --- name : " + name);
            switch (name) {
                case MANUFACTURER_HUAWEI:
                    goHuaWeiMainager(activity);
                    break;
                case MANUFACTURER_VIVO:
                    goVivoMainager(activity);
                    break;
                case MANUFACTURER_OPPO:
                    goOppoMainager(activity);
                    break;
                case MANUFACTURER_COOLPAD:
                    goCoolpadMainager(activity);
                    break;
                case MANUFACTURER_MEIZU:
                    goMeizuMainager(activity);
                    break;
                case MANUFACTURER_XIAOMI:
                    goXiaoMiMainager(activity);
                    break;
                case MANUFACTURER_SONY:
                    goSonyMainager(activity);
                    break;
                case MANUFACTURER_LG:
                    goLGMainager(activity);
                    break;
                default:
                    systemConfig(activity);
                    break;
            }
        }
    }

    /**
     * 系统设置界面
     */
    private static void systemConfig(Activity activity) {
        Intent intent = new Intent(Settings.ACTION_SETTINGS);
        activity.startActivityForResult(intent, PERMISSION_SETTING_FOR_RESULT);
    }

    private static void goHuaWeiMainager(Activity activity) {
        try {
            Intent intent = new Intent(activity.getPackageName());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName comp = new ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity");
            intent.setComponent(comp);
            activity.startActivityForResult(intent, PERMISSION_SETTING_FOR_RESULT);
        } catch (Exception e) {
            e.printStackTrace();
            systemConfig(activity);
        }

    }

    private static void goVivoMainager(Activity activity) {
        doStartApplicationWithPackageName(activity, "com.bairenkeji.icaller");
    }

    private static void goOppoMainager(Activity activity) {
        doStartApplicationWithPackageName(activity, "com.coloros.safecenter");
    }

    private static void goCoolpadMainager(Activity activity) {
        doStartApplicationWithPackageName(activity, "com.yulong.android.security:remote");
    }

    private static void goMeizuMainager(Activity activity) {
        try {
            Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.putExtra("packageName", activity.getPackageName());
            activity.startActivityForResult(intent, PERMISSION_SETTING_FOR_RESULT);
        } catch (ActivityNotFoundException localActivityNotFoundException) {
            localActivityNotFoundException.printStackTrace();
            systemConfig(activity);
        }

    }

    private static void goXiaoMiMainager(Activity activity) {
        String rom = getMiuiVersion();
        LogUtils.d("goMiaoMiMainager --- rom : " + rom);
        Intent intent = new Intent();
        if ("V6".equals(rom) || "V7".equals(rom)) {
            intent.setAction("miui.intent.action.APP_PERM_EDITOR");
            intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
            intent.putExtra("extra_pkgname", activity.getPackageName());
            activity.startActivityForResult(intent, PERMISSION_SETTING_FOR_RESULT);

        } else if ("V8".equals(rom) || "V9".equals(rom)) {
            intent.setAction("miui.intent.action.APP_PERM_EDITOR");
            intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
            intent.putExtra("extra_pkgname", activity.getPackageName());
            activity.startActivityForResult(intent, PERMISSION_SETTING_FOR_RESULT);
        } else {
            systemConfig(activity);
        }
    }

    private static String getMiuiVersion() {
        String propName = "ro.miui.ui.version.name";
        String line;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return line;

    }

    private static void goSonyMainager(Activity activity) {
        try {
            Intent intent = new Intent(activity.getPackageName());
            ComponentName comp = new ComponentName("com.sonymobile.cta", "com.sonymobile.cta.SomcCTAMainActivity");
            intent.setComponent(comp);
            activity.startActivityForResult(intent, PERMISSION_SETTING_FOR_RESULT);
        } catch (Exception e) {
            e.printStackTrace();
            systemConfig(activity);
        }

    }

    private static void goLGMainager(Activity activity) {
        try {
            Intent intent = new Intent(activity.getPackageName());
            ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.Settings$AccessLockSummaryActivity");
            intent.setComponent(comp);
            activity.startActivityForResult(intent, PERMISSION_SETTING_FOR_RESULT);
        } catch (Exception e) {
            e.printStackTrace();
            systemConfig(activity);
        }

    }

    private static void doStartApplicationWithPackageName(Activity activity, String packagename) {
        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = activity.getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return;
        }
        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);
        // 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveinfoList = activity.getPackageManager()
                .queryIntentActivities(resolveIntent, 0);
        LogUtils.d("PermissionPageManager resolveinfoList" + resolveinfoList.size());
        for (int i = 0; i < resolveinfoList.size(); i++) {
            LogUtils.d("PermissionPageManager " + resolveinfoList.get(i).activityInfo.packageName + resolveinfoList.get(i).activityInfo.name);
        }

        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if (resolveinfo != null) {
            // packageName参数2 = 参数 packName
            String packageName = resolveinfo.activityInfo.packageName;
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packageName参数2.mainActivityName]
            String className = resolveinfo.activityInfo.name;
            // LAUNCHER Intent
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            // 设置ComponentName参数1:packageName参数2:MainActivity路径
            ComponentName cn = new ComponentName(packageName, className);
            intent.setComponent(cn);
            try {
                activity.startActivityForResult(intent, PERMISSION_SETTING_FOR_RESULT);
            } catch (Exception e) {
                systemConfig(activity);
                e.printStackTrace();
            }
        }
    }
}
